"""
任务管理API
处理转换任务相关的请求
"""

import logging
from flask import request, jsonify, current_app
from . import api_bp
from ..services.task_service import TaskService
from ..services.user_service import UserService
from ..utils.auth_utils import require_auth, get_current_user, require_admin
from ..utils.validation_utils import ValidationUtils

logger = logging.getLogger(__name__)

@api_bp.route('/tasks', methods=['GET'])
@require_auth
def get_user_tasks():
    """
    获取用户任务列表
    
    Returns:
        JSON响应包含任务列表
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取查询参数
        status = request.args.get('status')
        limit = int(request.args.get('limit', 20))
        offset = int(request.args.get('offset', 0))
        sort_by = request.args.get('sort_by', 'created_at')
        sort_order = request.args.get('sort_order', 'desc')
        
        # 验证参数
        if limit > 100:
            limit = 100
        
        if sort_by not in ['created_at', 'updated_at', 'filename', 'status']:
            sort_by = 'created_at'
        
        if sort_order not in ['asc', 'desc']:
            sort_order = 'desc'
        
        # 获取任务列表
        task_service = TaskService(current_app)
        tasks_result = task_service.get_user_tasks(
            user_id, status, limit, offset, sort_by, sort_order
        )
        
        if not tasks_result['success']:
            return jsonify({'error': tasks_result['error']}), 400
        
        return jsonify({
            'success': True,
            'tasks': tasks_result['tasks'],
            'total': tasks_result['total'],
            'limit': limit,
            'offset': offset
        }), 200
        
    except Exception as e:
        logger.error(f"获取用户任务失败: {str(e)}")
        return jsonify({'error': '获取任务列表失败'}), 500

@api_bp.route('/tasks/<task_id>', methods=['GET'])
@require_auth
def get_task_details(task_id):
    """
    获取任务详情
    
    Args:
        task_id: 任务ID
        
    Returns:
        JSON响应包含任务详情
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取任务详情
        task_service = TaskService(current_app)
        task_result = task_service.get_task_status(task_id)
        
        if not task_result['success']:
            return jsonify({'error': task_result['error']}), 404
        
        task = task_result['task']
        
        # 检查权限（用户只能查看自己的任务，管理员可以查看所有任务）
        if task['user_id'] != user_id and current_user.get('role') != 'admin':
            return jsonify({'error': '无权限访问此任务'}), 403
        
        return jsonify({
            'success': True,
            'task': task
        }), 200
        
    except Exception as e:
        logger.error(f"获取任务详情失败: {str(e)}")
        return jsonify({'error': '获取任务详情失败'}), 500

@api_bp.route('/tasks/<task_id>/status', methods=['GET'])
@require_auth
def get_task_status(task_id):
    """
    获取任务状态
    
    Args:
        task_id: 任务ID
        
    Returns:
        JSON响应包含任务状态
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取任务状态
        task_service = TaskService(current_app)
        status_result = task_service.get_task_status(task_id)
        
        if not status_result['success']:
            return jsonify({'error': status_result['error']}), 404
        
        task = status_result['task']
        
        # 检查权限
        if task['user_id'] != user_id and current_user.get('role') != 'admin':
            return jsonify({'error': '无权限访问此任务'}), 403
        
        # 返回简化的状态信息
        status_info = {
            'task_id': task_id,
            'status': task['status'],
            'progress': task.get('progress', 0),
            'message': task.get('message', ''),
            'created_at': task['created_at'].isoformat() if task.get('created_at') else None,
            'updated_at': task['updated_at'].isoformat() if task.get('updated_at') else None,
            'estimated_completion': task.get('estimated_completion')
        }
        
        # 如果任务完成，添加下载信息
        if task['status'] == 'completed' and task.get('output_file_path'):
            status_info['download_available'] = True
            status_info['output_format'] = task.get('output_format')
            status_info['file_size'] = task.get('output_file_size')
        
        # 如果任务失败，添加错误信息
        if task['status'] == 'failed':
            status_info['error_message'] = task.get('error_message', '转换失败')
        
        return jsonify({
            'success': True,
            'status': status_info
        }), 200
        
    except Exception as e:
        logger.error(f"获取任务状态失败: {str(e)}")
        return jsonify({'error': '获取任务状态失败'}), 500

@api_bp.route('/tasks/<task_id>/cancel', methods=['POST'])
@require_auth
def cancel_task(task_id):
    """
    取消任务
    
    Args:
        task_id: 任务ID
        
    Returns:
        JSON响应包含取消结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取任务信息
        task_service = TaskService(current_app)
        task_result = task_service.get_task_status(task_id)
        
        if not task_result['success']:
            return jsonify({'error': task_result['error']}), 404
        
        task = task_result['task']
        
        # 检查权限
        if task['user_id'] != user_id and current_user.get('role') != 'admin':
            return jsonify({'error': '无权限操作此任务'}), 403
        
        # 检查任务状态
        if task['status'] in ['completed', 'failed', 'cancelled']:
            return jsonify({'error': '任务已完成或已取消，无法取消'}), 400
        
        # 取消任务
        cancel_result = task_service.cancel_task(task_id, user_id)
        
        if not cancel_result['success']:
            return jsonify({'error': cancel_result['error']}), 400
        
        logger.info(f"任务取消成功: {task_id} by {user_id}")
        
        return jsonify({
            'success': True,
            'message': '任务已取消'
        }), 200
        
    except Exception as e:
        logger.error(f"取消任务失败: {str(e)}")
        return jsonify({'error': '取消任务失败'}), 500

@api_bp.route('/tasks/<task_id>/retry', methods=['POST'])
@require_auth
def retry_task(task_id):
    """
    重试任务
    
    Args:
        task_id: 任务ID
        
    Returns:
        JSON响应包含重试结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取任务信息
        task_service = TaskService(current_app)
        task_result = task_service.get_task_status(task_id)
        
        if not task_result['success']:
            return jsonify({'error': task_result['error']}), 404
        
        task = task_result['task']
        
        # 检查权限
        if task['user_id'] != user_id and current_user.get('role') != 'admin':
            return jsonify({'error': '无权限操作此任务'}), 403
        
        # 检查任务状态
        if task['status'] not in ['failed', 'cancelled']:
            return jsonify({'error': '只能重试失败或已取消的任务'}), 400
        
        # 检查用户配额
        user_service = UserService(current_app)
        quota_result = user_service.check_quota(user_id)
        
        if not quota_result['success']:
            return jsonify({'error': quota_result['error']}), 400
        
        quota_info = quota_result['quota_info']
        if not quota_info['can_create_task']:
            return jsonify({'error': '已达到任务配额限制'}), 429
        
        # 重试任务
        retry_result = task_service.retry_task(task_id)
        
        if not retry_result['success']:
            return jsonify({'error': retry_result['error']}), 400
        
        logger.info(f"任务重试成功: {task_id} by {user_id}")
        
        return jsonify({
            'success': True,
            'message': '任务已重新开始',
            'estimated_duration': retry_result.get('estimated_duration', 60)
        }), 200
        
    except Exception as e:
        logger.error(f"重试任务失败: {str(e)}")
        return jsonify({'error': '重试任务失败'}), 500

@api_bp.route('/tasks/<task_id>', methods=['DELETE'])
@require_auth
def delete_task(task_id):
    """
    删除任务
    
    Args:
        task_id: 任务ID
        
    Returns:
        JSON响应包含删除结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取任务信息
        task_service = TaskService(current_app)
        task_result = task_service.get_task_status(task_id)
        
        if not task_result['success']:
            return jsonify({'error': task_result['error']}), 404
        
        task = task_result['task']
        
        # 检查权限
        if task['user_id'] != user_id and current_user.get('role') != 'admin':
            return jsonify({'error': '无权限操作此任务'}), 403
        
        # 检查任务状态
        if task['status'] in ['processing', 'queued']:
            return jsonify({'error': '无法删除正在处理的任务，请先取消'}), 400
        
        # 删除任务
        delete_result = task_service.delete_task(task_id)
        
        if not delete_result['success']:
            return jsonify({'error': delete_result['error']}), 400
        
        logger.info(f"任务删除成功: {task_id} by {user_id}")
        
        return jsonify({
            'success': True,
            'message': '任务已删除'
        }), 200
        
    except Exception as e:
        logger.error(f"删除任务失败: {str(e)}")
        return jsonify({'error': '删除任务失败'}), 500

@api_bp.route('/tasks/statistics', methods=['GET'])
@require_auth
def get_task_statistics():
    """
    获取任务统计信息
    
    Returns:
        JSON响应包含统计信息
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取统计信息
        task_service = TaskService(current_app)
        stats_result = task_service.get_user_statistics(user_id)
        
        if not stats_result['success']:
            return jsonify({'error': stats_result['error']}), 400
        
        return jsonify({
            'success': True,
            'statistics': stats_result['statistics']
        }), 200
        
    except Exception as e:
        logger.error(f"获取任务统计失败: {str(e)}")
        return jsonify({'error': '获取统计信息失败'}), 500

@api_bp.route('/tasks/batch', methods=['POST'])
@require_auth
def batch_task_operation():
    """
    批量任务操作
    
    Returns:
        JSON响应包含操作结果
    """
    try:
        current_user = get_current_user()
        if not current_user:
            return jsonify({'error': '用户未认证'}), 401
        
        user_id = current_user['id']
        
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少请求数据'}), 400
        
        task_ids = data.get('task_ids', [])
        operation = data.get('operation')
        
        if not task_ids or not operation:
            return jsonify({'error': '缺少必要参数'}), 400
        
        if operation not in ['cancel', 'delete', 'retry']:
            return jsonify({'error': '不支持的操作类型'}), 400
        
        if len(task_ids) > 50:
            return jsonify({'error': '批量操作最多支持50个任务'}), 400
        
        # 执行批量操作
        task_service = TaskService(current_app)
        results = []
        
        for task_id in task_ids:
            try:
                # 检查任务权限
                task_result = task_service.get_task_status(task_id)
                if not task_result['success']:
                    results.append({
                        'task_id': task_id,
                        'success': False,
                        'error': '任务不存在'
                    })
                    continue
                
                task = task_result['task']
                if task['user_id'] != user_id and current_user.get('role') != 'admin':
                    results.append({
                        'task_id': task_id,
                        'success': False,
                        'error': '无权限操作此任务'
                    })
                    continue
                
                # 执行操作
                if operation == 'cancel':
                    result = task_service.cancel_task(task_id, user_id)
                elif operation == 'delete':
                    result = task_service.delete_task(task_id)
                elif operation == 'retry':
                    result = task_service.retry_task(task_id)
                
                results.append({
                    'task_id': task_id,
                    'success': result['success'],
                    'error': result.get('error') if not result['success'] else None
                })
                
            except Exception as e:
                results.append({
                    'task_id': task_id,
                    'success': False,
                    'error': str(e)
                })
        
        # 统计结果
        success_count = sum(1 for r in results if r['success'])
        failed_count = len(results) - success_count
        
        logger.info(f"批量任务操作完成: {operation} - 成功: {success_count}, 失败: {failed_count}")
        
        return jsonify({
            'success': True,
            'operation': operation,
            'total': len(task_ids),
            'success_count': success_count,
            'failed_count': failed_count,
            'results': results
        }), 200
        
    except Exception as e:
        logger.error(f"批量任务操作失败: {str(e)}")
        return jsonify({'error': '批量操作失败'}), 500

# 管理员接口
@api_bp.route('/admin/tasks', methods=['GET'])
@require_admin
def admin_get_all_tasks():
    """
    管理员获取所有任务（管理员接口）
    
    Returns:
        JSON响应包含所有任务列表
    """
    try:
        # 获取查询参数
        status = request.args.get('status')
        user_id = request.args.get('user_id')
        limit = int(request.args.get('limit', 50))
        offset = int(request.args.get('offset', 0))
        sort_by = request.args.get('sort_by', 'created_at')
        sort_order = request.args.get('sort_order', 'desc')
        
        # 验证参数
        if limit > 200:
            limit = 200
        
        # 获取任务列表
        task_service = TaskService(current_app)
        tasks_result = task_service.get_all_tasks(
            status, user_id, limit, offset, sort_by, sort_order
        )
        
        if not tasks_result['success']:
            return jsonify({'error': tasks_result['error']}), 400
        
        return jsonify({
            'success': True,
            'tasks': tasks_result['tasks'],
            'total': tasks_result['total'],
            'limit': limit,
            'offset': offset
        }), 200
        
    except Exception as e:
        logger.error(f"管理员获取任务失败: {str(e)}")
        return jsonify({'error': '获取任务列表失败'}), 500

@api_bp.route('/admin/tasks/statistics', methods=['GET'])
@require_admin
def admin_get_task_statistics():
    """
    管理员获取系统任务统计（管理员接口）
    
    Returns:
        JSON响应包含系统统计信息
    """
    try:
        task_service = TaskService(current_app)
        stats_result = task_service.get_system_statistics()
        
        if not stats_result['success']:
            return jsonify({'error': stats_result['error']}), 400
        
        return jsonify({
            'success': True,
            'statistics': stats_result['statistics']
        }), 200
        
    except Exception as e:
        logger.error(f"获取系统统计失败: {str(e)}")
        return jsonify({'error': '获取统计信息失败'}), 500